package com.teamb6.shop.controller.front;

import com.google.code.kaptcha.Constants;
import com.teamb6.shop.common.UUIDUtils;
import com.teamb6.shop.domain.*;
import com.teamb6.shop.service.*;
import com.teamb6.shop.util.ImageUtil;
import com.teamb6.shop.util.Md5Util;
import com.teamb6.shop.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;


@Controller
@RequestMapping("users")
public class CustomerController {

    @Autowired
    private UserService userService;
    @Autowired
    private IndentService indentService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CateService cateService;


    @RequestMapping("/login")
    public String login(Model model){
        model.addAttribute("user",new User());
        model.addAttribute("errorMsg","邮箱");
        return "signin";
    }

    //跳转到注册页面
    @RequestMapping("/register")
    public String register(Model model){
        model.addAttribute("errorMsg","用户名");
        model.addAttribute("errorEmailMsg","邮箱");
        model.addAttribute("errorPasswordMsg","密码");
        model.addAttribute("user",new User());
        return "signup";
    }

    //输入用户信息并进行注册，密码使用MD5加密，此时用户状态为status暂未激活
    @RequestMapping("/registerfirst")
    public String registerResult(User user, Model model, @RequestParam("repassword") String rePassword){
        if(!rePassword.equals(user.getPassword()) ){
            model.addAttribute("errorMsg","用户名");
            model.addAttribute("errorEmailMsg","邮箱");
            model.addAttribute("errorPasswordMsg","密码不一致");
            return "signup";
        }

        List<User> userList;

        //用户密码加密
        user.setPassword(Md5Util.MD5Encode(user.getPassword(),"utf-8"));

        UserExample userExample = new UserExample();
        userExample.or().andUsernameLike(user.getUsername());
        userList = userService.selectByExample(userExample);
        if(!userList.isEmpty()){
            model.addAttribute("errorMsg","用户名被占用");
            model.addAttribute("errorEmailMsg","邮箱");
            model.addAttribute("errorPasswordMsg","密码");
            return "signup";
        }else{
            userExample.clear();
            userExample.or().andEmailLike(user.getEmail());
            userList = userService.selectByExample(userExample);
            if(!userList.isEmpty()){
                model.addAttribute("errorMsg","用户名");
                model.addAttribute("errorEmailMsg","邮箱已经被占用");
                model.addAttribute("errorPasswordMsg","密码");
                return "signup";
            }
            user.setStatus(0);
            String code = UUIDUtils.getUUID() + UUIDUtils.getUUID();
            user.setCode(code);
            Date Regtime = new Date();
            user.setRegtime(Regtime);
            if(!userService.insertUser(user)){
                model.addAttribute("errorMsg","用户名");
                model.addAttribute("errorEmailMsg","非法邮箱");
                model.addAttribute("errorPasswordMsg","密码");
                return "signup";
            }
        }
        return "signin";
    }

    /**
     * 校验邮箱中的code激活账户
     * 搜先根据激活码code查询用户，之后再把状态修改为“1”
     */
    @RequestMapping("/checkCode")
    public String checkCode(String code){
        System.out.println("--------------------------------------------------------");
        User user = userService.checkCode(code);
        System.out.println(user);
        if(user !=null){
            user.setStatus(1);
            user.setCode("");
            System.out.println(user);
            userService.updateUserStatus(user);
        }
        return "signin";
    }

    @RequestMapping("/loginconfirm")
    public String loginConfirm(User user, Model loginResult, HttpServletRequest request, @RequestParam("confirmlogo") String confirmlogo) {
        //进行用户密码MD5加密验证
        user.setPassword(Md5Util.MD5Encode(user.getPassword(), "UTF-8"));

        HttpSession session = request.getSession();
        String verificationCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!confirmlogo.equals(verificationCode)) {
            loginResult.addAttribute("errorMsg", "验证码错误");
            return "signin";

        }
        List<User> userList = new ArrayList<>();
        UserExample userExample = new UserExample();
        userExample.or().andEmailEqualTo(user.getEmail()).andPasswordEqualTo(user.getPassword()).andStatusEqualTo(1);
        userList = userService.selectByExample(userExample);

        if (!userList.isEmpty()) {
            session.setAttribute("user", userList.get(0));
            return "redirect:/main";
        } else {
            loginResult.addAttribute("errorMsg", "用户名与密码不匹配");
            loginResult.addAttribute("user",new User());
            return "signin";
        }
    }

    @Autowired
    private AddressService addressService;

    @RequestMapping("/info/address")
    public String address(HttpServletRequest request, Model addressModel) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
//        User user = new User();
//        user.setUserid(7);
        if (user == null) {
            return "redirect:/users/login";
        }

        return "person/address";
    }

    @RequestMapping("/addressjson")
    @ResponseBody
    public Msg showAddress(HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
//        User user = new User();
//        user.setUserid(7);

        if(user == null){
            return Msg.fail("请先登录");
        }

        AddressExample addressExample = new AddressExample();
        addressExample.or().andUseridEqualTo(user.getUserid());
        List<Address> addressList = addressService.getAllAddressByExample(addressExample);

        return Msg.success("查询成功").add("addressList",addressList);
    }

    @RequestMapping("/setDefault")
    @ResponseBody
    public Msg saveAddr(@RequestParam("default_id") Integer default_id, @RequestParam("address_id") Integer address_id) {
//        if(addresses.get(0).getConname() == null){
//            return Msg.fail("修改失败");
//        }
//        for(Address address : addresses){
//            addressService.updateByPrimaryKeySelective(address);
//        }
        addressService.updateByPrimaryKeySelective(new Address(default_id,0));
        addressService.updateByPrimaryKeySelective(new Address(address_id,1));
        return Msg.success("修改成功");
    }

    @RequestMapping("/saveAddr")
    @ResponseBody
    public Msg saveAddr(Address address) {
        addressService.updateByPrimaryKeySelective(address);
        return Msg.success("修改成功");
    }

    @RequestMapping("/insertAddr")
    @ResponseBody
    public Msg insertAddr(Address address, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
//        User user = new User();
//        user.setUserid(7);

        address.setUserid(user.getUserid());

        if(address.getAddressid() != null){
            addressService.updateByPrimaryKeySelective(address);
        }else {
            address.setStatus(0);
            addressService.insertSelective(address);
        }
        return Msg.success("添加成功").add("addressId",address.getAddressid());
    }

    @RequestMapping("/deleteAddr")
    @ResponseBody
    public Msg deleteAddr(Integer addressId) {
        addressService.deleteByPrimaryKey(addressId);
        return Msg.success("删除成功");
    }
    //跳转到用户个人中心
    @RequestMapping("/index")
    public String index(Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user == null){
            return "signin";
        }

        //最热商品前4个
        List<Goods> hotList = goodsService.getByHot();
        hotList.remove(5);
        hotList.remove(4);
        model.addAttribute("hotList",hotList);

        //用户待付款订单数量
        IndentExample notPayexample = new IndentExample();
        notPayexample.or().andUseridEqualTo(user.getUserid()).andIspayEqualTo((byte) 0);
        List<Indent> notPayList = indentService.selectIndentByExample(notPayexample);
        int notPayCount = notPayList.size();
        model.addAttribute("notPayCount",notPayCount);
        //用户待发货订单数量
        IndentExample notSendexample = new IndentExample();
        notSendexample.or().andUseridEqualTo(user.getUserid()).andIssendEqualTo((byte) 0).andIspayEqualTo((byte) 1);
        List<Indent> notSendList = indentService.selectIndentByExample(notSendexample);
        int notSendCount = notSendList.size();
        model.addAttribute("notSendCount",notSendCount);
        //用户待收货订单数量
        IndentExample notReceiveexample = new IndentExample();
        notReceiveexample.or().andUseridEqualTo(user.getUserid()).andIsreceiveEqualTo((byte) 0).andIssendEqualTo((byte) 1).andIspayEqualTo((byte) 1);
        List<Indent> notReceiveList = indentService.selectIndentByExample(notReceiveexample);
        int notReceiveCount = notReceiveList.size();
        model.addAttribute("notReceiveCount",notReceiveCount);
        //用户待评价订单数量
        IndentExample notCommentexample = new IndentExample();
        notCommentexample.or().andUseridEqualTo(user.getUserid()).andIscompleteEqualTo((byte) 0).andIsreceiveEqualTo((byte) 1).andIssendEqualTo((byte) 1).andIspayEqualTo((byte) 1);
        List<Indent> notCommentList = indentService.selectIndentByExample(notCommentexample);
        int notCommentCount = notCommentList.size();
        model.addAttribute("notCommentCount",notCommentCount);
        return "person/index";
    }

    @RequestMapping("/information")
    public String information(Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        Integer userId;
        User user = (User) session.getAttribute("user");
        if(user == null){
            return "signin";
        }
        userId = user.getUserid();
        user = userService.findUserByPrimaryKey(userId);
        model.addAttribute("user",user);
        return "person/information";
    }

    //用户编辑个人信息
    @PostMapping("/editUser")
    @ResponseBody
    public Msg editUser(User user,HttpServletRequest request){
        userService.editUser(user);
        request.getSession().setAttribute("user",user);
        return Msg.success("修改成功");
    }

    //用户跳转到安全页面
    @RequestMapping("/safe")
    public String safe(){
        return "person/safety";
    }

    //跳转到修改密码页面
    @RequestMapping("/password")
    public String password(){
        return "person/password";
    }

   //修改密码时验证用户输入的旧密码是否正确
    @PostMapping("/editCheck")
    @ResponseBody
    public Msg editPasswordCheck(User user){
       UserExample example = new UserExample();
       user.setPassword(Md5Util.MD5Encode(user.getPassword(),"utf-8"));
       example.or().andUseridEqualTo(user.getUserid()).andPasswordEqualTo(user.getPassword());
       List<User> userList = userService.selectByExample(example);
       if(userList.size()!=0){
           return Msg.success("");
       }else {
           return Msg.fail("原密码输入错误，请重新输入");
       }
    }

    //若旧密码输入正确，修改新密码
    @PostMapping("/editPassword")
    @ResponseBody
    public Msg updatePassword(User user,HttpServletRequest request){
        user.setPassword(Md5Util.MD5Encode(user.getPassword(),"utf-8"));
        userService.editUser(user);
        request.getSession().removeAttribute("user");
        return Msg.success("修改密码成功,请重新登录");
    }

    //跳转到用户订单管理页面
    @RequestMapping("/showOrder")
    public String orderList(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        //根据userId查到该用户所有的订单信息
        IndentExample example = new IndentExample();
        example.or().andUseridEqualTo(user.getUserid());
        List<Indent> indentList = indentService.selectIndentByExample(example);

        model.addAttribute("indentList",indentList);

        Indent indent;
        OrderItem orderItem;
        List<OrderItem> orderItemList;


        for (Integer i=0;i < indentList.size();i++){
            indent = indentList.get(i);
            //根据indent中的orderid在orderitem表中查到该用户的orderitem
            OrderItemExample orderItemExample = new OrderItemExample();
            orderItemExample.or().andOrderidEqualTo(indent.getOrderid());
            orderItemList = indentService.getOrderItemByExample(orderItemExample);

            List<Integer> goodsIdList = new ArrayList<>();
            List<Integer> goodsNumList = new ArrayList<>();
            //根据用户的orderitem中的goodsid拿到用户订单中所有的商品id,所购商品的数量
            for (Integer j=0;j < orderItemList.size();j++){
                orderItem = orderItemList.get(j);
                goodsIdList.add(orderItem.getGoodsid());
                goodsNumList.add(orderItem.getNum());
            }

            List<Goods> goodsList = new ArrayList<>();
            for(Integer k=0;k <goodsIdList.size();k++){
                List<ImagePath> imagePathList = goodsService.findImagePath(goodsIdList.get(k));
                Goods goods = goodsService.selectById(goodsIdList.get(k));
                Category category = cateService.findCategoryByPrimaryKey(goods.getCategory());
                goods.setIndentGoodsNum(goodsNumList.get(k));
                goods.setCateName(category.getCatename());
                goods.setImagePaths(imagePathList);
                goodsList.add(goods);
            }
//            GoodsExample goodsExample = new GoodsExample();
//            goodsExample.or().andGoodsidIn(goodsIdList);
//            goodsList = goodsService.selectByExample(goodsExample);
            indent.setGoodsInfo(goodsList);
            indentList.set(i,indent);
        }
        model.addAttribute("indentList",indentList);

        return "person/order";
    }

    //用户中心，用户删除订单
    @PostMapping("/deleteIndent")
    @ResponseBody
    public Msg deleteIndent(Indent indent){
        indentService.delectIndentById(indent.getOrderid());
        return Msg.success("删除成功");
    }

    //用户中心，用户确认收货
    @PostMapping("/confirmRev")
    @ResponseBody
    public Msg confirmRev(Integer orderid){
        Indent indent = indentService.selectByPrimaryKey(orderid);
        indent.setIsreceive(true);
        indentService.updateIndentByKey(indent);
        return Msg.success("订单信息已更新");
    }

    //修改头像
    @PostMapping("/queryImg")
    @ResponseBody
    public Msg queryImg(HttpSession session, @RequestParam MultipartFile file){
        User user = (User) session.getAttribute("user");

        String filename = file.getOriginalFilename();
        if(file != null){
            //进一步处理文件名，并将文件保存到本地目录中
            String ImagePath = ImageUtil.imagePath(file,filename);
            System.out.println("最后存入数据库的图片名字为："+ImagePath);
            //把图片路径存入到用户表中
            user.setPicpath(ImagePath);
            userService.editUser(user);
        }

        //返回修改后的user以及提示信息
        return Msg.success("上传图片成功").add("user",user);
    }

    //用户退出登录，刷新页面并清空session
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        return "redirect:/main";
    }
}